package com.horizon.common.configuration;

import com.horizon.common.entity.Token;
import com.horizon.common.util.SecrecyUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 全局跨域设置
 *
 * @author wangfuwei
 * @version 2018-08-13
 */
@Slf4j
@SpringBootConfiguration
public class CrosConfiguration {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin(tokenProperties().getOrigin()); // 1 设置访问源地址
        corsConfiguration.addAllowedHeader(tokenProperties().getHeader()); // 2 设置访问源请求头
        corsConfiguration.addAllowedMethod(tokenProperties().getMethod()); // 3 设置访问源请求方法
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }

    @Bean
    public CrosConfiguration.TokenProperties tokenProperties() {
        return new CrosConfiguration.TokenProperties();
    }

    @Getter
    @Setter
    @ConfigurationProperties("horizon.token")
    class TokenProperties {
        private long expiry = 1000 * 60 * 10;
        private String origin = "*";
        private String method = "*";
        private String header = "*";
        private String token = "authorization";
        private String secret = "";
        private String[] exclude = {"/login", "/login/**"};

        TokenProperties() {
            Token.TOKEN_KEY = this.token;
            Token.TOKEN_EXPIRY = this.expiry;
            try {
                this.secret = SecrecyUtil.generateAESKey();
                Token.SECRET_KEY = this.secret;
            } catch (Exception e) {
                e.printStackTrace();
                log.error("generateAESKey error", e);
            }
        }

        public void setToken(String token) {
            if (token != null && !token.isEmpty()) {
                this.token = token;
                Token.TOKEN_KEY = this.token;
            }
        }

        public void setSecret(String secret) {
            if (secret != null && !secret.isEmpty()) {
                this.secret = secret;
                Token.SECRET_KEY = this.secret;
            }
        }

        public void setExpiry(long expiry) {
            if (expiry > 0) {
                this.expiry = expiry;
                Token.TOKEN_EXPIRY = this.expiry;
            }
        }
    }
}
